package com.doupi.partner.util;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.util.LocationUtil;
import ch.qos.logback.core.util.OptionHelper;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import java.net.URL;

/**
 * logback配置加载
 * 
 * @author Alvin Wang
 * @version 1.0.0 on 2017-04-10
 */
public class LogbackConfigLoader implements ApplicationListener {
	private final static String DEFAULT_LOGBACK_FILE = "classpath:logback-debug.xml";

	private final static String PROPERTIES_ENV_KEY = "logback.config.file";

//	public LogbackConfigLoader() {
//		loadConfig();
//	}

	private void loadConfig() {
		try {
			LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
			String file = OptionHelper.getEnv(PROPERTIES_ENV_KEY);
			if (null == file) {
				file = OptionHelper.getSystemProperty(DEFAULT_LOGBACK_FILE, DEFAULT_LOGBACK_FILE);
			}
			URL url = LocationUtil.urlForResource(file);
			JoranConfigurator configurator = new JoranConfigurator();
			configurator.setContext(context);
			context.reset();
			configurator.doConfigure(url);
		} catch (Exception je) {
			// ignore should not appear
		}
	}

	@Override
	public void onApplicationEvent(ApplicationEvent applicationEvent) {
		loadConfig();
	}
}
